package com.itheima.file;

import com.itheima.file.util.HTTPHelper;
import com.itheima.file.util.PostMethodUtils;
import com.itheima.file.util.SslUtils;
import dm.jdbc.filter.stat.json.JSONObject;
import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;

import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.LinkedHashMap;

// @RunWith(SpringRunner.class)
// @SpringBootTest
public class ApiTestData {

    public static void main(final String[] args) throws Exception {
        // 忽略SSL证书验证的TrustManager
        TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                    }

                    public void checkServerTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                    }
                }
        };


        // 创建请求体
        JSONObject reqBodyObj = new JSONObject();
        reqBodyObj.put("app_id", "hcmcloud");
        reqBodyObj.put("table_name", ""); // 确保这里有一个有效的值
        reqBodyObj.put("stringDate", "20210301");
        reqBodyObj.put("condition", "1=1");

        // 设置Basic Authentication的凭证（用户名和密码）
        String username = "po_soap1";
        String password = "z123456789";

        final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope("httpbin.org", 80),
                new UsernamePasswordCredentials(username, password.toCharArray()));

        // String baseAuth = getBaseAuth(username, password);

        try (final CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .build()) {
            // final HttpGet httpget = new HttpGet("http://httpbin.org/basic-auth/admin/123456");
            SslUtils.ignoreSsl();
            // D:\developer\jdk-17.0.10\lib\security
            final HttpPost httpget = new HttpPost("https://podev.minmetals.com.cn:50001/RESTAdapter/BS_OA/BS_MDM/DeleteAssHrtree");
            // final HttpGet httpget = new HttpGet("https://segmentfault.com/a/1190000042354971#item-9");

            // 设置请求体
            final StringEntity reqEntity = new StringEntity(reqBodyObj.toString(), StandardCharsets.UTF_8);
            httpget.setEntity(reqEntity);
            System.out.println("执行请求" + httpget.getMethod() + " " + httpget.getUri());
            try (final CloseableHttpResponse response = httpclient.execute(httpget)) {
                System.out.println("----------------------------------------");
                System.out.println(response.getCode() + " " + response.getReasonPhrase());
                System.out.println(EntityUtils.toString(response.getEntity()));
            }
        }
    }

    /**
     * 401
     * @param args
     * @throws Exception
     */
    public static void main4(String[] args) throws Exception {
        // 设置Basic Authentication的凭证（用户名和密码）
        String username = "po_soap1";
        String password = "z123456789";
        final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope("httpbin.org", 80),
                new UsernamePasswordCredentials(username, password.toCharArray()));

        String baseAuth = getBaseAuth(username, password);
        // 计算基本认证编码
        // String auth = Base64.getEncoder().encodeToString(
        //         ("po_soap1" + ":" + "z123456789").getBytes(StandardCharsets.UTF_8)
        // );

        JSONObject reqBodyObj = new JSONObject();
        reqBodyObj.put("app_id", "hcmcloud");
        reqBodyObj.put("table_name", "");
        reqBodyObj.put("stringDate", "20210301");
        reqBodyObj.put("condition", "1=1");
        reqBodyObj.put("secretKey", "f3ac852124d2f991a3f63f2e33dae18b");

        LinkedHashMap<String, String> header = new LinkedHashMap<String, String>();
        // header.put("Authorization", "Basic " + credsProvider);
        header.put("Authorization", baseAuth);
        String postUrl = "https://podev.minmetals.com.cn:50001/RESTAdapter/BS_OA/BS_MDM/DeleteAssHrtree";
        try {
            SslUtils.ignoreSsl();
            String result = HTTPHelper.sendPOST(postUrl, reqBodyObj.toString(), header, "UTF-8");
            System.out.println(result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 响应401
     * @param args
     * @throws URISyntaxException
     */
    public static void main401(String[] args) throws URISyntaxException {
        // 设置Basic Authentication的凭证（用户名和密码）
        String username = "po_soap1";
        String password = "z123456789";
        final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope("httpbin.org", 80),
                new UsernamePasswordCredentials(username, password.toCharArray()));

        String baseAuth = getBaseAuth(username, password);

        JSONObject reqBodyObj = new JSONObject();
        reqBodyObj.put("app_id", "hcmcloud");
        reqBodyObj.put("table_name", "");
        reqBodyObj.put("stringDate", "20210301");
        reqBodyObj.put("condition", "1=1");
        reqBodyObj.put("secretKey", "f3ac852124d2f991a3f63f2e33dae18b");

        String postUrl = "https://podev.minmetals.com.cn:50001/RESTAdapter/BS_OA/BS_MDM/DeleteAssHrtree";

        // 计算基本认证编码
 /*       String auth = "Basic " + Base64.getEncoder().encodeToString(
                (username + ":" + password).getBytes(StandardCharsets.UTF_8)
        );*/

        // 设置HTTP头部
        LinkedHashMap<String, String> header = new LinkedHashMap<>();
        // header.put("Authorization", auth);
        header.put("Authorization", baseAuth);
        header.put("Content-Type", "application/json");

        // 发送请求（这里假设HTTPHelper.sendPOST方法支持自定义头部）
        try {
            SslUtils.ignoreSsl();
            String result = HTTPHelper.sendPOST(postUrl, reqBodyObj.toString(), header, "UTF-8");
            System.out.println(result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static String getBaseAuth(String userName, String password){
        String auth = userName + ":" + password;
        String base64Auth = cn.hutool.core.codec.Base64.encodeUrlSafe(auth.getBytes());
        return  "Basic " + base64Auth;
    }

    public static void main11(String[] args) {
        JSONObject reqBodyObj = new JSONObject();
        reqBodyObj.put("app_id", "hcmcloud");
        reqBodyObj.put("table_name", "");
        reqBodyObj.put("stringDate", "20210301");
        reqBodyObj.put("condition", "1=1");
        reqBodyObj.put("secretKey", "f3ac852124d2f991a3f63f2e33dae18b");
        String username = "po_soap1";
        String password = "z123456789";
        String postUrl = "https://podev.minmetals.com.cn:50001/RESTAdapter/BS_OA/BS_MDM/DeleteAssHrtree";
        String s = PostMethodUtils.sendPost(postUrl, reqBodyObj.toString(), username, password);
        System.out.println(s);
    }

}
